package com.grailsinaction

class PostController {

    def index = {
        if (!params.id) {
            params.id = 'cnorris'
        }
        println('redirecting...')
        redirect(action: 'timeline', params: params)
    }

    def postService
    def scaffold = true

    def timeline = {
        def user = User.findByUserId(params.id)
        def posts = Post.list(params)
        def postCount = Post.count()
        [user: user, postCount: postCount]
    }

    def addPost = {
        try {
            def newPost = postService.createPost(params.id, params.content)
            flash.message = "Added new post: ${newPost.content}"
        } catch (PostException pe) {
            flash.message = pe.message
        }
        redirect(action: 'timeline', id: params.id)
    }
}

/* Pre service method
    def addPost = {
        def user = User.findByUserId(params.id)
        if (user) {
            def post = new Post(params)
            user.addToPosts(post)
            if (user.save()) {
                println("timeline success")
                flash.message = "Successfully created Post"
            } else {
                println("timeline fail")
                user.discard()
                flash.message = "Invalid or empty post"
            }
        } else {
            println("timeline derp")
            flash.message = "Invalid user id"
        }
        redirect(action: 'timeline', id: params.id)
    }
}
*/
